package com.kehutong.admin.controler.app;

import com.kehutong.admin.service.UserHelper;
import com.kehutong.common.DoveClient;
import com.kehutong.common.entity.Root;
import com.kehutong.common.util.Token;
import org.coraframework.inject.Inject;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.util.Objects;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

@MvcAction
@ReqMapping("/kht-bin/permissions")
public class LoginAction {

    @Inject
    private DoveClient doveClient;
    @Inject
    private UserHelper userHelper;

    /**
     * 触发角色权限必须缓存当前登录账号的权限信息
     * @param token
     * @return
     * @throws Exception
     */
    @ReqMapping("/index")
    public Object index(Token token) throws Exception {
    	if (Objects.isNull(token)) {
    		return Result.unlogin();
    	}

        Set<String> pmsSet;
        if (Root.isRoot(token.getUuid())) {
            pmsSet = new HashSet<>();
            pmsSet.add("*");
        } else {
            pmsSet = userHelper.getPermissions(Root.isRoot(token.getUuid()), new ArrayList<>(token.getRoles()), true).keySet();
        }
        token.setPermissions(pmsSet);
        change(token.getSessionId(), pmsSet);

        return Result.success();
    }

    public void change(String id, Set<String> pemissions) throws Exception {
        doveClient.post("/kht-bin/session/service/change", http->{
            http.addParam("id", id);
            http.addParam("permissions", String.join(",", pemissions));
        });
    }
}